package com.jinlejia.erp.ui.mine.contract


import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.TypeReference
import com.freedom.yefeng.yfrecyclerview.YfListMode
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener
import com.jinlejia.erp.R
import com.jinlejia.erp.base.ApiConfig
import com.jinlejia.erp.base.MapCallBack
import com.jinlejia.erp.bean.SaleRecordBean
import com.jinlejia.erp.bean.ShareShopAndAgentBean
import com.jinlejia.erp.databinding.FragmentSaleRecordingBinding
import com.jinlejia.erp.ui.common.ProgressDialog
import com.jinlejia.erp.ui.mine.adapter.RecordingListAdapter
import com.jinlejia.erp.utils.CallUtils
import com.jinlejia.erp.utils.DataFilter
import com.jinlejia.erp.utils.DateUtil
import com.jzxiang.pickerview.TimePickerDialog
import com.jzxiang.pickerview.data.Type
import com.weight.CustomToast
import com.weight.mp3.AudioController
import com.zhy.http.okhttp.OkHttpUtils
import okhttp3.Call
import okhttp3.MediaType
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber

/**
 * A simple [Fragment] subclass.
 * 出售/出租录音
 */
class SaleRecordingFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {

    private lateinit var binding: FragmentSaleRecordingBinding
    private lateinit var dataList: ArrayList<String>

    //region 筛选入参
    private var millis: Long = 0
    private var state: String? = null
    private var shareStoreCode: String? = null
    private var userPin: String? = null
    private var pageIndex: Int = 1
    //endregion

    private lateinit var audioController: AudioController
    private val dataArray = ArrayList<SaleRecordBean>()
    private lateinit var adapter: RecordingListAdapter
    private var phoneNO = ""//手机号
    private var mLoadingLock = false//是否正在加载
    private var nextPageAvailable = false//是否有下一页
    //region 接口返回经纪人和共享店的集合
    private val userNameList: ArrayList<String> by lazy { ArrayList<String>() }

    private val userPinList: ArrayList<String> by lazy { ArrayList<String>() }

    private val shareStoreCodeList: ArrayList<String> by lazy { ArrayList<String>() }

    private val shareStoreNameList: ArrayList<String> by lazy { ArrayList<String>() }

    private val shareStoreAdnAgentList: ArrayList<ShareShopAndAgentBean> by lazy { ArrayList<ShareShopAndAgentBean>() }
    //endregion

    private lateinit var  progressdialog : ProgressDialog
    private var isPostTime = false//是否带着时间参数去请求

    private lateinit var type: String


    fun newInstance(type: String): SaleRecordingFragment {
        val fragment = SaleRecordingFragment()
        val args = Bundle()
        args.putString("type", type)
        fragment.arguments = args
        return fragment
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_sale_recording, container, false)
        binding.event = this
        EventBus.getDefault().register(this)
        initView()
        return binding.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        audioController = AudioController(context)
    }

    override fun onDetach() {
        audioController.release()
        super.onDetach()
    }

    //region 初始化数据和控件
    private fun initView() {
        if (!this::progressdialog.isInitialized){
            this.progressdialog = ProgressDialog(context,"请稍后",false)
        }
        adapter = RecordingListAdapter(this.dataArray,this.audioController,binding.recyclerView)
        type = arguments!!.getString("type").toString()
        millis = System.currentTimeMillis()
        dataList = ArrayList()
        dataList.add("全部")
        dataList.add("未保护")
        dataList.add("已保护")
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow)
        binding.refreshLayout.setOnRefreshListener(this)

        adapter.changeMode(YfListMode.MODE_LOADING)
        binding.recyclerView.enableAutoLoadMore(this)
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.layoutManager = LinearLayoutManager(activity)
        binding.recyclerView.adapter = this.adapter

        this.adapter.setOnCallListener {
            phoneNO = it
            CallUtils.CallTel(activity!!, phoneNO)
        }

        this.adapter.setOnSetAsProtecteionListener { tvType, btnProtect, state, followId ->
            if (state == "设为保护") {
                updataRecordingState(btnProtect, tvType, followId, "4")
            } else if (state == "取消保护") {
                updataRecordingState(btnProtect, tvType, followId, "3")
            }
        }
        getData()
    }
    //endregion

    //region 点击事件
    private lateinit var calendarPicker:TimePickerDialog
    fun onClick(view: View) {
        when (view.id) {
            R.id.LayoutRecordingDate -> {
                //region UI操作
                binding.tvRecordingDate.setTextColor(Color.parseColor("#F0B800"))
                binding.imRecordingDate.setImageResource(R.mipmap.ic_my_recording_true)

                binding.tvRecordingState.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingState.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingSharedShop.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingSharedShop.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingAgent.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingAgent.setImageResource(R.mipmap.ic_my_recording_false)
                //endregion
                //region 时间选择框

                if (!this::calendarPicker.isInitialized){
                    this.calendarPicker = TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("录音日期")
                        .setCurrentMillseconds(millis)
                        .setThemeColor(resources.getColor(R.color.yellow))
                        .setWheelItemTextNormalColor(resources.getColor(R.color.hintColor))
                        .setWheelItemTextSelectorColor(resources.getColor(R.color.black))
                        .setCallBack { timePickerView, millseconds ->
                            if (!progressdialog.isShowing){
                                progressdialog.show()
                            }
                            millis = millseconds
                            isPostTime = true
                            pageIndex = 1
                            getData()
                            binding.tvRecordingDate.text = DateUtil.getTime(millseconds, "yyyy-MM-dd").toString()
                        }
                        .build()
                }
                calendarPicker.show(fragmentManager!!, "year_month_date")
                //endregion
            }
            R.id.LayoutRecordingState -> {
                //region UI操作
                binding.tvRecordingState.setTextColor(Color.parseColor("#F0B800"))
                binding.imRecordingState.setImageResource(R.mipmap.ic_my_recording_true)

                binding.tvRecordingDate.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingDate.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingSharedShop.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingSharedShop.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingAgent.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingAgent.setImageResource(R.mipmap.ic_my_recording_false)
                //endregion
                val pickerView = SheetWheelPickerViewOne(context, dataList, "保护状态")
                pickerView.setOnSelectListener {
                    if (!progressdialog.isShowing){
                        progressdialog.show()
                    }
                    state = it
                    pageIndex = 1
                    getData()
                    binding.tvRecordingState.text = state
                }
                pickerView.show()
            }
            R.id.LayoutRecordingAgent -> {
                //region UI操作
                binding.tvRecordingAgent.setTextColor(Color.parseColor("#F0B800"))
                binding.imRecordingAgent.setImageResource(R.mipmap.ic_my_recording_true)

                binding.tvRecordingDate.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingDate.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingState.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingState.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingSharedShop.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingSharedShop.setImageResource(R.mipmap.ic_my_recording_false)
                //endregion
                shareStoreAdnAgentList.clear()
                for (i in 0 until userNameList.size) {
                    val shareShopAndAgentBean = ShareShopAndAgentBean()
                    shareShopAndAgentBean.name = userNameList[i]
                    shareShopAndAgentBean.code = userPinList[i]
                    shareStoreAdnAgentList.add(shareShopAndAgentBean)
                }
                val intent = Intent(context, SharedStoreAndAgentListActivity().javaClass)
                val bundle = Bundle()
                bundle.putSerializable("AgentdataList", shareStoreAdnAgentList)
                intent.putExtras(bundle)
                intent.putExtra("title", "经纪人")
                startActivity(intent)
            }
            R.id.LayoutRecordingSharedShop -> {
                //region UI操作
                binding.tvRecordingSharedShop.setTextColor(Color.parseColor("#F0B800"))
                binding.imRecordingSharedShop.setImageResource(R.mipmap.ic_my_recording_true)

                binding.tvRecordingDate.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingDate.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingState.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingState.setImageResource(R.mipmap.ic_my_recording_false)

                binding.tvRecordingAgent.setTextColor(Color.parseColor("#1A1A1A"))
                binding.imRecordingAgent.setImageResource(R.mipmap.ic_my_recording_false)
                //endregion
                shareStoreAdnAgentList.clear()
                for (i in 0 until shareStoreNameList.size) {
                    val shareShopAndAgentBean = ShareShopAndAgentBean()
                    shareShopAndAgentBean.name = shareStoreNameList[i]
                    shareShopAndAgentBean.code = shareStoreCodeList[i]
                    shareStoreAdnAgentList.add(shareShopAndAgentBean)
                }
                val intent = Intent(context, SharedStoreAndAgentListActivity().javaClass)
                val bundle = Bundle()
                bundle.putSerializable("ShareShopdataList", shareStoreAdnAgentList)
                intent.putExtras(bundle)
                intent.putExtra("title", "共享店")
                startActivity(intent)
            }
            else -> {
            }
        }
    }

    //endregion

    //region 请求录音列表数据
    private fun getData() {
        mLoadingLock = true
        val json = JSONObject()
        if (isPostTime) {
            json["followTime"] = DateUtil.getTime(millis, "yyyy-MM-dd").toString()
        }
        if (!TextUtils.isEmpty(state)) {
            when (state) {
                "全部" -> json.remove("followState")
                "已保护" -> json["followState"] = 4
                "未保护" -> json["followState"] = 3
            }

        }

        if (!TextUtils.isEmpty(shareStoreCode)) {
            json["shareStoreCode"] = shareStoreCode
        }

        if (!TextUtils.isEmpty(userPin)) {
            json["userPin"] = userPin
        }
        json["pageIndex"] = pageIndex
        json["pageSize"] = 5
        json["type"] = type
        OkHttpUtils.postString()
            .mediaType(MediaType.parse("application/json; charset=utf-8"))
            .url(ApiConfig.RecordingList)
            .content(json.toJSONString())
            .build()
            .execute(object : MapCallBack() {
                override fun onError(call: Call?, e: Exception?, id: Int) {
                    e?.printStackTrace()
                    if (progressdialog.isShowing){
                        progressdialog.dismiss()
                    }
                    if (binding.refreshLayout.isRefreshing) {
                        binding.refreshLayout.isRefreshing = false
                    }
                }

                override fun onResponse(response: MutableMap<String, Any>?, id: Int) {
                    if (progressdialog.isShowing){
                        progressdialog.dismiss()
                    }
                    audioController.onPause()
                    val filter = DataFilter.filter(context, response, adapter)
                    if (filter) {
                        val data = JSON.parseObject(response?.get("data")!!.toString())
                        //数据列表
                        val list: java.util.ArrayList<Map<String, Any>> =
                            JSON.parseObject(
                                data.getJSONArray("recordResultList").toString(),
                                object :
                                    TypeReference<java.util.ArrayList<Map<String, Any>>>() {})

                        val userNameListArray = data.getJSONArray("userNameList").toArray()
                        userNameList.clear()
                        for (userName: Any in userNameListArray) {
                            userNameList.add(userName.toString())
                        }

                        val userPinListArray = data.getJSONArray("userPinList").toArray()
                        userPinList.clear()
                        for (ping: Any in userPinListArray) {
                            userPinList.add(ping.toString())
                        }

                        val shareStoreNameListArray =
                            data.getJSONArray("shareStoreNameList").toArray()
                        shareStoreNameList.clear()
                        for (shareStoreName: Any in shareStoreNameListArray) {
                            shareStoreNameList.add(shareStoreName.toString())
                        }

                        val shareStoreCodeListArray =
                            data.getJSONArray("shareStoreCodeList").toArray()
                        shareStoreCodeList.clear()
                        for (shareStoreCode: Any in shareStoreCodeListArray) {
                            shareStoreCodeList.add(shareStoreCode.toString())
                        }

                        val list2 = arrayListOf<SaleRecordBean>()
                        for (m in list.iterator()){
                            val bean = SaleRecordBean()
                            bean.followId = m["followId"].toString()
                            bean.followTime = m["followTime"].toString().toLong()
                            bean.userName = m["userName"].toString()
                            bean.shareStoreName = m["shareStoreName"].toString()
                            bean.followState = m["followState"].toString()
                            bean.followContent = m["followContent"].toString()
                            bean.callingId = m["callingId"].toString()
                            list2.add(bean)
                        }
                        if (pageIndex == 1) {
                            adapter.data = list2
                        } else {
                            adapter.addData(list2)
                        }

                        nextPageAvailable = data["nextPageAvailable"] as Boolean
                        if (!nextPageAvailable) {
                            //没有更多
                            pageIndex--
                        }
                    }

                    if (binding.refreshLayout.isRefreshing) {
                        binding.refreshLayout.isRefreshing = false
                    }
                    mLoadingLock = false

                }

            })

    }
    //endregion

    //region 修改录音状态接口请求
    private fun updataRecordingState(
        btnState: Button,
        tvType: TextView,
        followId: String,
        state: String
    ) {

        OkHttpUtils.get()
            .url(ApiConfig.UpdateRecordingState)
            .addParams("followId", followId)
            .addParams("state", state)
            .build()
            .execute(object : MapCallBack() {
                override fun onError(call: Call?, e: java.lang.Exception?, id: Int) {
                    CustomToast.showToast(context, "网络错误" + e.toString(), 1500)
                }

                override fun onResponse(response: MutableMap<String, Any>?, id: Int) {
                    if (DataFilter.filter(context, response)) {
                        if (state == "3") {
                            tvType.text = "未保护"
                            btnState.text = "设为保护"
                        } else if (state == "4") {
                            tvType.text = "已保护"
                            btnState.text = "取消保护"
                        }
                        CustomToast.showToast(context,"修改录音状态成功",1500)
                    }
                }

            })

    }

    //endregion

    override fun onRefresh() {
        pageIndex = 1
        getData()
    }

    override fun loadMore() {
        if (nextPageAvailable) {
            if (mLoadingLock) {
                return
            }
            mLoadingLock = true
            pageIndex++
            adapter.addFooter("loading")

            getData()
        } else {
            adapter.addFooter(R.string.is_all)
        }
    }

    @Subscriber(tag = "TAG_ShareShopCode")
    private fun changeShareCode(bean: ShareShopAndAgentBean) {
        if (!progressdialog.isShowing){
            progressdialog.show()
        }
        shareStoreCode = bean.code
        pageIndex = 1
        getData()
        binding.tvRecordingSharedShop.text = bean.name
    }

    @Subscriber(tag = "TAG_AgentPing")
    private fun changeAgentPing(bean: ShareShopAndAgentBean) {
        if (!progressdialog.isShowing){
            progressdialog.show()
        }
        userPin = bean.code
        pageIndex = 1
        getData()
        binding.tvRecordingAgent.text = bean.name
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}
